﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using FluentNHibernate.Automapping;
using FluentNHibernate.Conventions.Helpers;

namespace PrinterBudi.Persistence
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();

                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008
                            .ConnectionString(c =>
                                    c.FromConnectionStringWithKey("SQLExpress")))
                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<PBTransactionMap>())
                    .ExposeConfiguration(config =>
                    {
                        SchemaExport schemaExport = new SchemaExport(config);
                        schemaExport.Drop(false, false);
                        schemaExport.Create(false, false);
                    })
                    .BuildSessionFactory();

        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}